package cn.dw.mm.utils;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

public class FileUpAndDown {
	public boolean uploadFile(HttpServletRequest request, String fileName, String fileFullPath) throws IllegalStateException, IOException {
		
        File[] matchFiles = FileUtils.searchFile(new File(fileFullPath), fileName);//如果找到同名的文件，报错
        if (matchFiles.length > 0) {
        	return false;
		}
    	//将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
        		request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request))
        {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
           //获取multiRequest 中所有的文件名
            Iterator<String> iter=multiRequest.getFileNames();
             
            while(iter.hasNext())
            {
                //一次遍历所有文件
                MultipartFile file=multiRequest.getFile(iter.next().toString());
                if(file!=null)
                {
                	String tempfileName = file.getOriginalFilename();
                	String sub = tempfileName.substring(tempfileName.indexOf(".") + 1);//分离出文件后缀名
                    File myPath = new File(fileFullPath + "/");  
                    if ( !myPath.exists()){//若此目录不存在，则创建之  
                        myPath.mkdir();   
                    }  
                	String path = fileFullPath + "/" + fileName + "." + sub;//路径+文件名+后缀名
                    //上传
                    file.transferTo(new File(path));
                }
                 
            }
           
        }
        return true;
	}
	
	public boolean deleteFile(String fileName, String fileFullPath) {
		File[] matchFiles = FileUtils.searchFile(new File(fileFullPath), fileName);
    	if (matchFiles.length == 1) {
    		matchFiles[0].delete();
    		System.out.println("Delete success.");
    		return true;
    	} else {
    		System.out.println("Delete fail.Duplicate files or file not found.");
    		return false;
		}
	}
}
